package api

import (
	"ims/app/dao"
	"ims/app/model"
	"ims/app/ws"
	"ims/tools/response"

	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
)

//查询客服信息
func Kefuinfo(r *ghttp.Request) {
	kefuId := r.GetString("kefu_id")

	user := dao.FindUserById(r, kefuId)
	info := make(map[string]interface{})
	info["name"] = user.Nickname
	info["id"] = user.Name
	info["avator"] = user.Avator
	response.JsonResponse(r, g.Map{
		"code":   200,
		"msg":    "ok",
		"result": info,
	})
}

//查询在线的客服和访客 列表
func GetKefusVisitorsOnline(r *ghttp.Request) {

	kefuName := r.GetString("kefu_name")
	roleId := r.Get("kefu_id")
	users := make([]*model.VisitorOnline, 0)
	visitorIds := make([]string, 0)
	for uid, visitor := range ws.ClientList {
		if visitor.To_id != kefuName && roleId.(float64) != 2 {
			//continue
		}
		userInfo := new(model.VisitorOnline)
		userInfo.Uid = uid
		userInfo.Username = visitor.Name
		userInfo.Avator = visitor.Avator
		users = append(users, userInfo)
		visitorIds = append(visitorIds, visitor.Id)
	}

	//查询最新消息
	messages := dao.FindLastMessage(visitorIds)
	temp := make(map[string]string, 0)
	for _, mes := range messages {
		temp[mes.VisitorId] = mes.Content
	}
	for _, user := range users {
		user.LastMessage = temp[user.Uid]
		if user.LastMessage == "" {
			user.LastMessage = "新访客"
		}
	}

	tcps := make([]string, 0)
	for ip, _ := range clientTcpList {
		tcps = append(tcps, ip)
	}
	response.JsonResponse(r, g.Map{
		"code":   200,
		"msg":    "ok",
		"result": users,
	})
}

//查看 其他客服人员列表
func OtherKefulist(r *ghttp.Request) {

	idStr := r.Get("kefu_id")
	id := idStr.(float64)
	result := make([]interface{}, 0)
	ws.SendPingToKefuClient()
	kefus := dao.FindUsers()
	for _, kefu := range kefus {
		if uint(id) == uint(kefu.Id) {
			//continue
		}

		item := make(map[string]interface{})
		item["name"] = kefu.Name
		item["nickname"] = kefu.Nickname
		item["avator"] = kefu.Avator
		item["status"] = "offline"
		kefus, ok := ws.KefuList[kefu.Name]
		if ok && len(kefus) != 0 {
			item["status"] = "online"
		}
		result = append(result, item)
	}
	response.JsonResponse(r, g.Map{
		"code":   200,
		"msg":    "ok",
		"result": result,
	})

}

//转发访客给其他客服
func GetTransKefu(r *ghttp.Request) {
	kefuId := r.GetQueryString("kefu_id")
	visitorId := r.GetQueryString("visitor_id")
	curKefuId := r.GetQueryString("kefu_name")

	user := dao.FindUser(kefuId)
	visitor := dao.FindVisitorByVistorId(visitorId)
	if user.Name == "" || visitor.Name == "" {
		response.JsonResponse(r, g.Map{
			"code": 400,
			"msg":  "访客或客服不存在",
		})
		return
	}
	dao.UpdateVisitorKefu(visitorId, kefuId)
	ws.UpdateVisitorUser(visitorId, kefuId)
	go ws.VisitorOnline(kefuId, visitor)
	go ws.VisitorOffline(curKefuId, visitor.VisitorId, visitor.Name)
	go ws.VisitorNotice(visitor.VisitorId, "客服转接到"+user.Nickname)
	response.JsonResponse(r, g.Map{
		"code": 200,
		"msg":  "转移成功",
	})
}
